<template>
  <el-cascader
    v-model="model"
    :props="props"
    :options="options"
    filterable
    @clear="handleClear"
    :before-filter="handleBeforeFilter"
  />
</template>

<script lang="ts" setup>
import { dictRegionApi } from "@/api/region/os-dict-region/index";
import type { DictRegionModel } from "@/api/region/os-dict-region/types";
import type { CascaderOption, CascaderProps } from "element-plus";
import type Node from "element-plus/es/components/cascader-panel/src/node.mjs";
import { ref } from "vue";

const model = defineModel<string[]>();
// 配置项
const props: CascaderProps = {
  lazy: true, // 开启懒加载
  checkStrictly: true, // 选择任意一级选项
  lazyLoad(node: Node, resolve: (data: CascaderOption[]) => void) {
    dictRegionApi
      .findList({
        parentId: node.data?.regionId as string,
      })
      .then(({ data }) => {
        resolve(returnOptions(data.results));
      });
  },
};

// 清除树形选择
const handleClear = () => {
  model.value = [];
  options.value = [];
};

const options = ref<CascaderOption[]>([]);
// 数据过滤
const handleBeforeFilter = (value: string) => {
  dictRegionApi
    .findList({
      likeRegionName: value,
    })
    .then(({ data }) => {
      options.value = returnOptions(data.results);
    });
  return false;
};

const returnOptions = (list: DictRegionModel[]): CascaderOption[] => {
  return list.map((item) => {
    return {
      label: item.regionName,
      value: item.regionCode,
      regionId: item.regionId,
      leaf: !item.hasChildren,
    };
  });
};
</script>
